﻿using System;
using System.Collections.Generic;
using Idea.UnitOfWork.Interface;

namespace Idea.UnitOfWork
{
    /// <summary>
    /// Base implementation of Unit of Work Manager;
    /// responsible for manage Unit of Works in application.
    /// </summary>
    public class UnitOfWorkManager : IUnitOfWorkManager
    {
        public Stack<IUnitOfWork> Stack { get; private set; }

        /// <summary>
        /// Constructor of Unit of work manager
        /// </summary>
        public UnitOfWorkManager()
        {
            Stack = new Stack<IUnitOfWork>();
        }

        /// <summary>
        /// Add Unit of Work to stact of open Unit of works
        /// </summary>
        public IUnitOfWork AddOpenUnitOfWork(IUnitOfWork uow)
        {
            Stack.Push(uow);
            return uow;
        }

        /// <summary>
        /// Close last open Unit of work
        /// </summary>
        public IUnitOfWork CloseLastUnitOfWork()
        {
            return Stack.Pop();
        }

        /// <summary>
        /// Get current Unit of work
        /// </summary>
        public IUnitOfWork GetCurrentUnitOfWork()
        {
            if (Stack.Count == 0)
            {
                throw new IndexOutOfRangeException("None Unit of Work is currently open.");
            }
            return Stack.Peek();
        }
    }
}
